package com.geminisystems.service;

import com.geminisystems.entity.ProductGroup;
import com.geminisystems.exception.EntityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Dmitry
 */
public class GroupServiceImpl implements GroupService {
    
    public static Map<Long, ProductGroup> entities = new HashMap<Long, ProductGroup>();
    public static long increment = 0L;

    public synchronized Long saveGroup(ProductGroup group) throws EntityException {
        if(group == null) throw new EntityException("Product Group shouldn't be null");
        if(group.getId() == null) {
            group.setId(++increment);
        } 
        entities.put(group.getId(), group);
        return group.getId();
    }

    public synchronized void deleteGroup(ProductGroup group) throws EntityException {
        if(group == null || group.getId() == null) throw new EntityException("Product Group shouldn't be null or should persist");
        entities.remove(group.getId());
    }

    public synchronized ProductGroup getGroupById(Long id) {
        return cloneGroup(entities.get(id));
    }

    public synchronized List<ProductGroup> getGroups() {
        List<ProductGroup> result = new ArrayList<ProductGroup>();
        for(ProductGroup group : entities.values()) {
            result.add(cloneGroup(group));
        }
        return result;
    }

    public synchronized List<ProductGroup> findGroupByName(String str) {
        List<ProductGroup> result = new ArrayList<ProductGroup>();
        for(ProductGroup group : entities.values()) {
            if(group.getName().contains(str)) {
                result.add(cloneGroup(group));
            }
        }
        return result;
    }
    
    public synchronized  void deleteGroups(List<Long> ids){
        for(Long id : ids) {
            entities.remove(id);
        }
    }
    
    private synchronized ProductGroup cloneGroup(ProductGroup group) {
        if(group == null) return null;
        ProductGroup result = new ProductGroup();
        result.setId(group.getId());
        result.setName(group.getName());
        result.setDescription(group.getDescription());
        return result;
    }
    
    public synchronized void insertNewData() throws EntityException {
        ProductGroup group = new ProductGroup();
        group.setName("Group01");
        group.setDescription("Group description 01");
        saveGroup(group);
        group = new ProductGroup();
        group.setName("Group02");
        group.setDescription("Group description 02");
        saveGroup(group);
        group = new ProductGroup();
        group.setName("Group02");
        group.setDescription("Group description 02");
        saveGroup(group);
        
    }
    
}
